import axios from 'axios';
import { ElMessage } from 'element-plus';
interface downLoadFileBlobType {
	url: string;
	method: string;
	params?: any;
}
/**
 * @description: 下载文件
 * @param {downLoadFileBlobType} data
 * @return {*} void 返回文件流
 */
export const downLoadFileBlob = (data: downLoadFileBlobType) => {
	if (data.method.toLowerCase() === 'get') {
		axios({
			url: data.url, //下载地址
			method: data.method, //请求方式
			responseType: 'blob', //返回类型
			params: data.params
		}).then((res: any) => {
			console.log('res', res);
			try {
				const debug = res.data;
				if (debug) {
					const elink = document.createElement('a');
					//获取文件名
					const contentDisposition: string = res.headers.get('Content-Disposition');

					const filename: string = contentDisposition.split('filename=')[1];
					//解决乱码
					const temp = decodeURIComponent(filename);
					elink.download = temp;
					elink.style.display = 'none';
					var blob = new Blob([debug], { type: 'application/x-msdownload' });
					elink.href = URL.createObjectURL(blob);
					document.body.appendChild(elink);
					elink.click();
					document.body.removeChild(elink);
				} else {
					console.log('下载失败');
				}
			} catch (e) {
				console.log('e', e);

				ElMessage({
					type: 'warning',
					message: '下载失败，文件不存在！'
				});
			}
		});
	} else {
		axios({
			url: data.url, //下载地址
			method: data.method, //请求方式
			responseType: 'blob', //返回类型
			data: data.params
		}).then((res: any) => {
			console.log('res', res);
			try {
				const debug = res.data;
				if (debug) {
					const elink = document.createElement('a');
					//获取文件名
					const contentDisposition: string = res.headers.get('Content-Disposition');

					const filename: string = contentDisposition.split('filename=')[1];
					//解决乱码
					const temp = decodeURIComponent(filename);
					elink.download = temp;
					elink.style.display = 'none';
					var blob = new Blob([debug], { type: 'application/x-msdownload' });
					elink.href = URL.createObjectURL(blob);
					document.body.appendChild(elink);
					elink.click();
					document.body.removeChild(elink);
				} else {
					console.log('下载失败');
				}
			} catch (e) {
				console.log('e', e);

				ElMessage({
					type: 'warning',
					message: '下载失败，文件不存在！'
				});
			}
		});
	}
};
